package com.hec.yygh.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hec.yygh.common.utils.JwtHelper;
import com.hec.yygh.enums.AuthStatusEnum;
import com.hec.yygh.model.user.Patient;
import com.hec.yygh.model.user.UserInfo;
import com.hec.yygh.user.mapper.UserInfoMapper;
import com.hec.yygh.user.service.PatientService;
import com.hec.yygh.user.service.UserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hec.yygh.vo.user.LoginVo;
import com.hec.yygh.vo.user.UserAuthVo;
import com.hec.yygh.vo.user.UserInfoQueryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import javax.print.DocPrintJob;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author hec
 * @since 2022-11-21
 */
@Slf4j
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private PatientService patientService;

    @Override
    public Map<String, Object> login(LoginVo loginVo){
        log.info("loginVo==============="+loginVo);
        //1、获得手机号和验证码信息
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //2、判断手机号或者验证码是否为空
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){
//            throw new Exception("手机号或者验证码为空");
            return null;
        }
        //3、redis中的验证比较
        String code_num = redisTemplate.opsForValue().get(phone);
        log.info("code_num================"+code_num);
        if (!code_num.equals(code)){
            return null;
        }


        //4、判断是不是首次登录，如果是首次登录，完成自动注册功能
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getPhone,phone);
        UserInfo userInfo = this.getOne(queryWrapper);
        if (userInfo == null){
            UserInfo info = new UserInfo();
            info.setPhone(phone);
            info.setStatus(1);
            info.setCreateTime(new Date());
            this.save(info);
        }
        //5、判断用户状态
        if (userInfo.getStatus()==0){
//            throw new Exception("该账户被锁定");
            return null;
        }
        //6、返回用户信息
        //返回页面显示名称
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("name", name);
        map.put("token", token);
        return map;
    }

    @Override
    public UserInfo getUserInfo(Long userId) {
        UserInfo byId = this.getById(userId);
        Map<String,Object> param = new HashMap<>();
        String statusNameByStatus = AuthStatusEnum.getStatusNameByStatus(byId.getAuthStatus());
        param.put("authStatusString",statusNameByStatus);
        byId.setParam(param);
        return byId;
    }

    @Override
    public void saveUserAuth(UserAuthVo userAuthVo, Long userId) {
        UserInfo userInfo = this.getById(userId);
        //设置认证信息
        //认证人姓名
        userInfo.setName(userAuthVo.getName());
        //其他认证信息
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        this.updateById(userInfo);
    }

    @Override
    public Page<UserInfo> selectUserInfoPage(Long page, Long limit, UserInfoQueryVo userInfoQueryVo) {
        Page<UserInfo> objectPage = new Page<>(page, limit);
        //UserInfoQueryVo获取条件值
        String name = userInfoQueryVo.getKeyword(); //用户名称
        Integer status = userInfoQueryVo.getStatus();//用户状态
        Integer authStatus = userInfoQueryVo.getAuthStatus(); //认证状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin(); //开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd(); //结束时间
        //对条件值进行非空判断
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("name",name).or().eq("phone",name);
        }
        if(!StringUtils.isEmpty(status)) {
            wrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(authStatus)) {
            wrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }
        //调用mapper的方法
        //调用mapper的方法
        Page<UserInfo> userInfoPage = baseMapper.selectPage(objectPage, wrapper);
        userInfoPage.getRecords().stream().forEach((obj) -> {
            //处理认证状态编码
            obj.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(obj.getAuthStatus()));
            //处理用户状态 0  1
            String statusString = obj.getStatus().intValue() == 0 ? "锁定" : "正常";
            obj.getParam().put("statusString", statusString);
        });

        return userInfoPage;
    }

    @Override
    public void lock(Long userId, Integer status) {
        if(status.intValue() == 0 || status.intValue() == 1) {
            UserInfo userInfo = this.getById(userId);
            userInfo.setStatus(status);
            this.updateById(userInfo);
        }
    }

    @Override
    public Map<String, Object> show(Long id) {
        Map<String,Object> map = new HashMap<>();
        //根据userid查询用户信息
        UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(id));
        map.put("userInfo",userInfo);
        //根据userid查询就诊人信息
        List<Patient> patientList = patientService.findAllUserId(id);
        map.put("patientList",patientList);
        return map;
    }

    @Override
    public void approval(Long id, Integer authStatus) {
        //认证审批  2通过  -1不通过
        if(authStatus.intValue()==2 || authStatus.intValue()==-1) {
            UserInfo userInfo = baseMapper.selectById(id);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }

    //编号变成对应值封装
    private UserInfo packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus().intValue()==0 ?"锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }
}
